package com.jy.rhin.infra.repo.document.submission.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jy.framework.base.entity.Page;
import com.jy.framework.base.utils.Converter;
import com.jy.framework.base.utils.DateUtil;
import com.jy.rhin.domain.exception.RhinInfraErrorType;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentEntryMapper;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentEntryStaticsMapper;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentSubmissionSetMapper;
import com.jy.rhin.infra.repo.document.submission.po.DocumentEntryPO;
import com.jy.rhin.infra.uitl.Asserts;
import com.jy.rhin.sdk.dto.document.statistic.*;
import com.jy.starter.repository.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dhl
 * @date 2022/6/10
 * @Description 文档汇总统计查询handler
 */
@Slf4j
@Service
public class DocumentStatisticsQueryHandler {

    @Resource
    private DocumentEntryMapper documentEntryMapper;
    @Resource
    private DocumentSubmissionSetMapper documentSubmissionSetMapper;
    @Resource
    private DocumentEntryStaticsMapper documentEntryStaticsMapper;
    static final String FORMAT = "yyyy-MM-dd-HH:mm:ss";

    /**
     * 查询提交集总数
     */
    public Long queryDocumentSetTotal() {
        Integer count = documentSubmissionSetMapper.selectCount(new QueryWrapper<>());
        return count.longValue();
    }

    /**
     * 查询文档元数据总数
     */
    public Long queryDocumentEntryTotal() {
        Integer count = documentEntryMapper.selectCount(new QueryWrapper<>());
        return count.longValue();
    }

    /**
     * 查询文档日新增数: 统计昨天的新增数
     */
    public Long queryDocumentEntryTotalByDay() {
        //当天零点
        Date endTime = Converter.toDate(DateUtil.getTodayStart(), FORMAT);
        //昨天零点
        Date startTime = DateUtils.addDays(endTime, -1);
        QueryWrapper<DocumentEntryPO> queryWrapper = new QueryWrapper<>();
        //creationTime ∈ [startTime, endTime)
        queryWrapper.lambda()
                .ge(DocumentEntryPO::getCreationTime, startTime)
                .lt(DocumentEntryPO::getCreationTime, endTime);
        Integer count = documentEntryMapper.selectCount(queryWrapper);
        return count.longValue();
    }

    /**
     * 根据文档类型汇总文档数，以及日增数
     */
    public List<GetTotalGroupTypeRespDto> queryDocumentEntryTotalGroupType() {
        //当天零点
        Date endTime = Converter.toDate(DateUtil.getTodayStart(), FORMAT);
        //昨天零点
        Date startTime = DateUtils.addDays(endTime, -1);
        //creationTime ∈ [startTime, endTime)
        return documentEntryMapper.queryDocumentEntryTotalGroupType(startTime, endTime);
    }

    /**
     * 每日新增趋势图，查询指定时间范围内，每日文档新增数，以及对应日期的文档总数
     * 1. 查询开始日期前，文档总数
     * 2. 查询每日新增数
     * 3. 合并两个结果集
     */
    public List<GetTotalGroupDayRespDto> queryDocumentEntryTotalGroupDay(GetTotalGroupDayReqDto req) {
        Asserts.gt(req.getJieShuRQ(), req.getKaiShiRQ(), RhinInfraErrorType.PARAM_DATE_VALUE_ERROR);
        QueryWrapper<DocumentEntryPO> totalQw = new QueryWrapper<>();
        totalQw.lambda().lt(DocumentEntryPO::getCreationTime, req.getKaiShiRQ());
        //开始日期之前的文档总数
        Long total = Long.valueOf(documentEntryMapper.selectCount(totalQw));
        //时间范围内每天新增文档数
        Date startTime = Converter.toDate(String.valueOf(req.getKaiShiRQ()));
        Date endTime = DateUtils.addDays(Converter.toDate(String.valueOf(req.getJieShuRQ())), 1);
        //creationTime ∈ [kaiShiRQ, jieShuRQ)
        List<GetTotalGroupDayRespDto> result = documentEntryMapper.queryDocumentEntryTotalGroupDay(startTime, endTime);
        Map<Date, GetTotalGroupDayRespDto> dayRespMap = result.stream().distinct().collect(Collectors.toMap(GetTotalGroupDayRespDto::getRiQi, resp -> resp));

        int dayCount = 0;
        try {
            dayCount = DateUtil.dateBetween(startTime, endTime);
        } catch (ParseException e) {
            log.error("时间转换异常，结果错误");
        }

        List<GetTotalGroupDayRespDto> respList = new ArrayList<>();
        for (int i = 0; i < dayCount; i++) {
            Date date = DateUtils.addDays(startTime, i);
            GetTotalGroupDayRespDto dayResp = dayRespMap.get(date);
            if(ObjectUtils.isNull(dayResp)){
                dayResp = new GetTotalGroupDayRespDto();
                dayResp.setRiQi(date);
                dayResp.setRiZengShu(0L);
            }
            Long riZengShu = dayResp.getRiZengShu();
            total += riZengShu;
            dayResp.setZongShu(total);
            respList.add(dayResp);
        }
        return respList;
    }

    /**
     * 统计各医疗机构的文档数及日新增数
     */
    public Page<FindOrgListRespDto> queryOrgListGroupOrgName(FindOrgListReqDto dto) {
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(dto.getOrgName()), "org_name", dto.getOrgName())
        .orderByDesc("wendangZS")
                .groupBy("orgName");
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Object> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(dto.getPageNo(), dto.getPageSize(), true);
        //当天零点
        Date endTime = Converter.toDate(DateUtil.getTodayStart(), FORMAT);
        //昨天零点
        Date startTime = DateUtils.addDays(endTime, -1);
        //creationTime ∈ [startTime, endTime)
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<FindOrgListRespDto> pageResult = documentEntryStaticsMapper.queryOrgListGroupOrgName(page, queryWrapper, startTime, endTime);
        return PageUtils.page(pageResult);
    }

}
